import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_circle_option.dart';
import 'package:qunaimedical/components/item_doctor.dart';
import 'package:qunaimedical/components/item_rounded_option.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/components/top_banner.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/doctor.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/auth.dart';
import 'package:qunaimedical/pages/consultation.dart';
import 'package:qunaimedical/pages/consultation_records.dart';
import 'package:qunaimedical/pages/course/course_page.dart';
import 'package:qunaimedical/pages/doctor_list.dart';
import 'package:qunaimedical/pages/doctor_simple_detail.dart';
import 'package:qunaimedical/pages/login.dart';
import 'package:qunaimedical/pages/news/health_home.dart';
import 'package:qunaimedical/pages/padding_page.dart';
import 'package:qunaimedical/pages/patient_manage/patient_list.dart';
import 'package:qunaimedical/pages/public_consultation_record_list.dart';
import 'package:qunaimedical/pages/timely_consultation_list.dart';
import 'package:qunaimedical/pages/timely_consultation_public_list.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/event_bus_manager.dart';
import 'package:qunaimedical/utils/log_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:sprintf/sprintf.dart';

class SummaryPage extends StatefulWidget {
  @override
  _SummaryPageState createState() => _SummaryPageState();
}

class _SummaryPageState extends State<SummaryPage> {
  String _tag = '_SummaryPageState';

  final List<String> _gridImages = [
    'assets/images/ic_option_doctor.png',
    'assets/images/ic_option_history.png',
    'assets/images/ic_option_group.png',
    'assets/images/ic_option_im.png',
    'assets/images/ic_option_history2.png',
    'assets/images/ic_option_consulting_hall.png',
    'assets/images/ic_option_news.png',
    'assets/images/ic_option_school.png',
  ];

  final List<String> _gridTitles = [
    '群爱名医',
    '会诊记录',
    '专家群组',
    '即时咨询',
    '接诊记录',
    '咨询大厅',
    '健康资讯',
    '群爱讲堂',
  ];

  List<Doctor> _doctorList = [];
  StreamSubscription _notifier;

  @override
  void initState() {
    super.initState();
    _fetchDoctorList();
    _notifier = eventBus.on<EventBusManager>().listen((event) {
      // 收到个人信息刷新事件
      if (event.eventKey == EventBusManager.profileRefresh) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _notifier.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: [
        SliverToBoxAdapter(child: TopBanner()),
        SliverToBoxAdapter(
          child: Container(
            color: Colors.white,
            padding:
                const EdgeInsets.only(top: 10, right: 5, left: 5, bottom: 15),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              children: [
                Expanded(
                  child: ItemRoundedOption(
                    bgColor: Color(0xff64D4A4),
                    text: '预约会诊',
                    imagePath: 'assets/images/ic_option_reserve.png',
                    onTap: () {
                      if (_checkPermission()) {
                        Navigator.pushNamed(
                            context, ConsultationPage.routeName);
                      }
                    },
                  ),
                ),
                Expanded(
                  child: ItemRoundedOption(
                    bgColor: Color(0xff2E7BF4),
                    text: '患者管理',
                    imagePath: 'assets/images/ic_option_patient.png',
                    onTap: () {
                      if (_checkPermission()) {
                        Navigator.pushNamed(context, PatientListPage.routeName);
                      }
                    },
                  ),
                ),
                Expanded(
                  child: ItemRoundedOption(
                    bgColor: Colors.orangeAccent,
                    text: '会诊大厅',
                    imagePath: 'assets/images/ic_option_home.png',
                    onTap: () {
                      Navigator.pushNamed(
                          context, PublicConsultationRecordListPage.routeName);
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
        SliverGrid(
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int position) {
              return ItemCircleOption(
                imagePath: _gridImages[position],
                text: _gridTitles[position],
                onTap: () {
                  switch (position) {
                    case 0:
                      Navigator.pushNamed(context, DoctorListPage.routeName);
                      break;
                    case 1:
                      if (SPUtils.getUser() == null) {
                        _loginTip();
                      } else {
                        Navigator.pushNamed(
                            context, ConsultationRecordsPage.routeName);
                      }
                      break;
                    case 3:
                      if (SPUtils.getUser() == null) {
                        _loginTip();
                      } else {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (c) => TimelyConsultationListPage()));
                      }
                      break;
                    case 5:
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (c) => TimelyConsultationPublicList()));
                      break;
                    case 6:
                      Navigator.push(context,
                          MaterialPageRoute(builder: (c) => NewsHomePage()));
                      break;
                    case 7:
                      Navigator.push(context,
                          MaterialPageRoute(builder: (c) => CoursePage()));
                      break;
                    default:
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (c) =>
                                  PaddingPage(_gridTitles[position])));
                  }
                },
              );
            },
            childCount: _gridImages.length,
          ),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4,
            childAspectRatio: 0.9,
          ),
        ),
        _buildCertificationTip(),
        SliverToBoxAdapter(child: CustomDivider()),
        _buildDoctorList(),
      ],
    );
  }

  void _loginTip() {
    DialogUtils.showAlertDialog(context, '提示', '您需要登录后才可以使用该功能。',
        onPressed: () {
      Navigator.pop(context);
      Navigator.pushNamed(context, LoginPage.routeName);
    });
  }

  /// 检查权限，登录+认证
  bool _checkPermission() {
    User user = SPUtils.getUser();
    if (user == null) {
      _loginTip();
      return false;
    } else {
      // 认证: 未认证或者认证失败时，提示用户进行认证。
      if (user.authStatus == 2 || user.authStatus == 4) {
        DialogUtils.showAlertDialog(context, '提示', '请先进行资质认证', onPressed: () {
          Navigator.pop(context);
          Navigator.pushNamed(context, AuthPage.routeName).then((value) {
            CommonUtils.refreshProfile(context);
          });
        });
        return false;
      }
      // 认证： 待认证时，提示用户等待
      if (user.authStatus == 3) {
        DialogUtils.showAlertDialog(context, '提示', '已提交资料，请等待审核。');
        return false;
      }
      return true;
    }
  }

  /// 认证提示
  Widget _buildCertificationTip() {
    return SliverToBoxAdapter(
      child: Offstage(
        offstage: context.read<StoreInfo>().user != null &&
            (context.read<StoreInfo>().user.authStatus == 1 ||
                context.read<StoreInfo>().user.authStatus == 3),
        child: Container(
          color: Colors.white,
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Text(
                      '您可以进行资质认证',
                      style: TextStyle(color: Colors.yellow[800]),
                    ),
                    Text(
                      '资质认证通过后可以使用更多功能',
                      style: TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              ),
              ElevatedButton(
                onPressed: () {
                  User user = SPUtils.getUser();
                  if (user == null) {
                    _loginTip();
                  } else {
                    Navigator.pushNamed(context, AuthPage.routeName)
                        .then((value) {
                      CommonUtils.refreshProfile(context);
                    });
                  }
                },
                child: Text('资质认证 >'),
                style: ButtonStyle(
                  shape: MaterialStateProperty.all(
                    RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(50),
                    ),
                  ),
                  backgroundColor: MaterialStateProperty.all(
                    Colors.yellow[800],
                  ),
                  elevation: MaterialStateProperty.all(0),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 医生列表
  Widget _buildDoctorList() {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          if (index == 0) {
            return Container(
              height: 60,
              child: PrimaryLabel(
                '群爱名医',
                trailing: InkWell(
                  child: Row(
                    children: [
                      Text(
                        '更多',
                        style: TextStyle(fontSize: 16, color: Colors.grey),
                      ),
                      Icon(
                        CupertinoIcons.right_chevron,
                        color: Colors.grey,
                        size: 18,
                      )
                    ],
                  ),
                  onTap: () {
                    Navigator.pushNamed(context, DoctorListPage.routeName);
                  },
                ),
              ),
            );
          }
          return ItemDoctor(
            _doctorList[index - 1],
            onFavorite: () {
              if (_doctorList[index - 1].whetherAppointed == '0') {
                _addFavorite(index - 1);
              } else {
                _removeFavorite(index - 1);
              }
            },
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (c) => DoctorSimpleDetailPage(
                          doctorId: _doctorList[index - 1].id))).then((value) {
                // 跳转回来刷新医生列表。
                _fetchDoctorList();
              });
            },
          );
        },
        childCount: _doctorList.length + 1,
      ),
    );
  }

  void _fetchDoctorList() async {
    Map<String, dynamic> params = {};
    if (SPUtils.getUser() != null) {
      params['doctorAccountId'] = SPUtils.getUser().id;
    }
    var result =
        await XHttp.postJson(sprintf(Urls.DOCTOR_LIST, [1, 3]), params);
    if (result != null) {
      var response = MapResponse.fromJson(result);
      if (response.code == 1) {
        var records = (response.data['records'] as List)
            .map((e) => Doctor.fromJson((e as Map<String, dynamic>)))
            .toList();
        Log.d(_tag, 'records: $records');
        if (mounted) {
          setState(() {
            _doctorList = records;
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _addFavorite(int index) async {
    User user = SPUtils.getUser();
    if (user != null) {
      DialogUtils.showWaitDialog(context);
      var data = await XHttp.postJson(Urls.FAVORITE_ADD, {
        'accountId': user.id,
        'recordId': _doctorList[index].id,
        'recordType': 'doctor',
      });
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          if (mounted) {
            setState(() {
              _doctorList[index].whetherAppointed = '1';
            });
          }
        }
      }
    }
  }

  void _removeFavorite(int index) async {
    User user = SPUtils.getUser();
    if (user != null) {
      DialogUtils.showWaitDialog(context);
      var data = await XHttp.postJson(Urls.FAVORITE_REMOVE, {
        'accountId': user.id,
        'recordId': _doctorList[index].id,
      });
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          if (mounted) {
            setState(() {
              _doctorList[index].whetherAppointed = '0';
            });
          }
        }
      }
    }
  }
}
